package com.compty.core.framework.util;

import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字串工具类
 * @author kingapex
 * 2010-1-6下午01:52:58
 */
public class StringUtil {
	
	
	
	private StringUtil(){}
	
	
	/**
	 * 检测某字串是否存在某数组中
	 * @param value
	 * @param array
	 * @return 存在返回真，不存在返回假
	 */
	public static boolean isInArray(String value ,String[] array){
		 if(array==null)return false;
		 for(String v :array){
			 if(v.equals(value)) return true;
		 }
		 return false;
		
	}
	
	
	
	public static boolean isInArray(int value ,String[] array){
		 if(array==null)return false;
		 for(String v :array){
			 if( Integer.valueOf(v).intValue() == value ) return true;
		 }
		 return false;
		
	}
	
	
	
	
	/**
	 * 将数组成str连接成字符串
	 * @param str
	 * @param array
	 * @return
	 */
	public static String implode(String str, Object[] array){
		if(str == null || array == null){
			return "";
		}
		String result = "";
		for(int i = 0; i < array.length; i++){
			if(i == array.length - 1){
				result += array[i].toString();
			}else{
				result += array[i].toString() + str;
			}
		}
		return result;
	}
	

	
	public static String implodeValue(String str, Object[] array){
		if(str == null || array == null){
			return "";
		}
		String result = "";
		for(int i = 0; i < array.length; i++){
			if(i == array.length - 1){
				result += "?";
			}else{
				result += "?" + str;
			}
		}
		return result;
	}
	

	/**
	 * MD5加密方法
	 * 
	 * @param str
	 *            String
	 * @return String
	 */
	public static String md5(String content) {
	    if(content == null) return null;
		
		byte[] source = content.getBytes();
		String s = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(source);

			byte tmp[] = md.digest();
			char str[] = new char[16 * 2];

			int k = 0;
			for (int i = 0; i < 16; i++) { // 

				byte byte0 = tmp[i];

				str[k++] = hexDigits[byte0 >>> 4 & 0xf];

				str[k++] = hexDigits[byte0 & 0xf];
			}
			s = new String(str);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return s;
	}

	/**
	 * 验证Email地址是否有效
	 * 
	 * @param sEmail
	 * @return
	 */
	public static boolean validEmail(String sEmail) {
		String pattern = "^([a-z0-9A-Z]+[-|\\.|_]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		return sEmail.matches(pattern);
	}
	
	/**
	 * 验证手机号是否有效
	 * 
	 * @param sEmail
	 * @return
	 */
	public static boolean validMobile(String sMobile) {
		if(sMobile == null) return false;
		String pattern = "^(13[0-9]|15[0-9]|18[0-9])[0-9]{8}$";
		return sMobile.matches(pattern);
	}

	/**
	 * 验证字符最大长度
	 * 
	 * @param str
	 * @return
	 */
	public static boolean validMaxLen(String str, int length) {
		if (str == null || str.equals("")) {
			return false;
		}
		if (str.length() > length) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 验证字符最小长度
	 * 
	 * @param str
	 * @return
	 */
	public static boolean validMinLen(String str, int length) {
		if (str == null || str.equals("")) {
			return false;
		}
		if (str.length() < length) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 验证一个字符串是否为空
	 * 
	 * @param str
	 * @return 如果为空返回真，如果不为空返回假 
	 */
	
	public static  boolean isEmpty(String str){
		if(str==null || "".equals(str)) return true; 
		
		String pattern ="\\S";
		Pattern p = Pattern.compile(pattern, 2 | Pattern.DOTALL);
		Matcher m = p.matcher(str);
		return !m.find();
		
	 
	}	
	
	/**
	 * 验证两个字符串是否相等且不能为空
	 * 
	 * @param str1
	 * @param str2
	 * @return
	 */
	public static boolean equals(String str1, String str2) {
		if (str1 == null || str1.equals("") || str2 == null || str2.equals("")) {
			return false;
		}
		return str1.equals(str2);
	}

	/**
	 * 将字符型转为Int型
	 * 
	 * @param str
	 * @return
	 */
	public static int toInt(String str) {
		int value = 0;
		if (str == null || str.equals("")) {
			return 0;
		}
		try {
			value = Integer.parseInt(str);
		} catch (Exception ex) {
			value = 0;
			ex.printStackTrace();
		}
		return value;
	}

	/**
	 * 把数组转换成String
	 * 
	 * @param array
	 * @return
	 */
	public static String arrayToString(Object[] array, String split) {
		if (array == null) {
			return "";
		}
		String str = "";
		for (int i = 0; i < array.length; i++) {
			if (i != array.length - 1) {
				str += array[i].toString() + split;
			} else {
				str += array[i].toString();
			}
		}
		return str;
	}
	
	/**
	 * 将一个list转为以split分隔的string
	 * @param list
	 * @param split
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String listToString(List list,String split){
		if(list == null || list.isEmpty()) return "";
		StringBuffer sb = new StringBuffer();
		for(Object obj:list){
			 if(sb.length()!=0 ){
				 sb.append(split);
			 }
			sb.append(obj.toString());
			
		}
		return sb.toString();
	}

	/**
	 * 得到WEB-INF的绝对路径
	 * 
	 * @return
	 */
	public static String getWebInfPath() {
		String filePath = Thread.currentThread().getContextClassLoader()
				.getResource("").toString();
		if (filePath.toLowerCase().indexOf("file:") > -1) {
			filePath = filePath.substring(6, filePath.length());
		}
		if (filePath.toLowerCase().indexOf("classes") > -1) {
			filePath = filePath.replaceAll("/classes", "");
		}
		if (System.getProperty("os.name").toLowerCase().indexOf("window") < 0) {
			filePath = "/" + filePath;
		}
		if (!filePath.endsWith("/"))
			filePath += "/";
		return filePath;
	}

	/**
	 * 得到根目录绝对路径(不包含WEB-INF)
	 * 
	 * @return
	 */
	public static String getRootPath() {
//		return "E:/javatool/apache-tomcat-6.0.18/webapps/user_test";
	String filePath = Thread.currentThread().getContextClassLoader()
				.getResource("").toString();
		if (filePath.toLowerCase().indexOf("file:") > -1) {
			filePath = filePath.substring(6, filePath.length());
		}
		if (filePath.toLowerCase().indexOf("classes") > -1) {
			filePath = filePath.replaceAll("/classes", "");
		}
		if (filePath.toLowerCase().indexOf("web-inf") > -1) {
			filePath = filePath.substring(0, filePath.length() - 9);
		}
		if (System.getProperty("os.name").toLowerCase().indexOf("window") < 0) {
			filePath = "/" + filePath;
		}

		if (filePath.endsWith("/"))
			filePath= filePath.substring(0, filePath.length()-1);

		return filePath;
	}

	
	public static String getRootPath(String resource) {
		String filePath = Thread.currentThread().getContextClassLoader()
				.getResource(resource).toString();
		if (filePath.toLowerCase().indexOf("file:") > -1) {
			filePath = filePath.substring(6, filePath.length());
		}
//		if (filePath.toLowerCase().indexOf("classes") > -1) {
//			filePath = filePath.replaceAll("/classes", "");
//		}
//		if (filePath.toLowerCase().indexOf("web-inf") > -1) {
//			filePath = filePath.substring(0, filePath.length() - 9);
//		}
		if (System.getProperty("os.name").toLowerCase().indexOf("window") < 0) {
			filePath = "/" + filePath;
		}

		if (!filePath.endsWith("/"))
			filePath += "/";

		return filePath;
	}
	
	/**
	 * 格式化页码
	 * 
	 * @param page
	 * @return
	 */
	public static int formatPage(String page) {
		int iPage = 1;
		if (page == null || page.equals("")) {
			return iPage;
		}
		try {
			iPage = Integer.parseInt(page);
		} catch (Exception ex) {
			iPage = 1;
		}
		return iPage;
	}

	/**
	 * 将计量单位字节转换为相应单位
	 * 
	 * @param size
	 * @return
	 */
	public static String getFileSize(String fileSize) {
		String temp = "";
		DecimalFormat df = new DecimalFormat("0.00");
		double dbFileSize = Double.parseDouble(fileSize);
		if (dbFileSize >= 1024) {
			if (dbFileSize >= 1048576) {
				if (dbFileSize >= 1073741824) {
					temp = df.format(dbFileSize / 1024 / 1024 / 1024) + " GB";
				} else {
					temp = df.format(dbFileSize / 1024 / 1024) + " MB";
				}
			} else {
				temp = df.format(dbFileSize / 1024) + " KB";
			}
		} else {
			temp = df.format(dbFileSize / 1024) + " KB";
		}
		return temp;
	}

	/**
	 * 得到一个32位随机字符
	 * 
	 * @return
	 */
	public static String getEntry() {
		Random random = new Random(100);
		Date now = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(new String(
				"yyyyMMddHHmmssS"));
		return md5(formatter.format(now) + random.nextDouble());
	}
	
	/**
	 *@Todo:判断是否为整数
	 *@CreateTime:2011-9-19 下午05:16:14
	 * @param str
	 */
	public static boolean isDigit(String str) {
		if(str == null) return false;
		if("".equals(str)) return false;
		char[] charArray = str.toCharArray();
		for (int i = 0; i < charArray.length; i++) {
			if(!Character.isDigit(charArray[i])){
				return false;
			}
		}
		return true;
	}
	
	/**
	 *@Todo:判断是否为数字
	 */
	public static boolean isNumber(String str) {
		if(str == null) return false;
	    Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?");
	    Matcher matcher = pattern.matcher(str);
	    boolean b= matcher.matches();
	    if(b){
	    	return true;
	    }
		return false;
	}

	/**
	 * 将中文汉字转成UTF8编码
	 * @param str
	 * @return
	 */
	public static String toUTF8(String str) {
		if (str == null || str.equals("")) {
			return "";
		}
		try {
			return new String(str.getBytes("ISO8859-1"), "UTF-8");
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
	}
	
	
	public static String to(String str,String charset) {
		if (str == null || str.equals("")) {
			return "";
		}
		try {
			return new String(str.getBytes("ISO8859-1"),charset);
		} catch (Exception ex) {
			ex.printStackTrace(); 
			return "";
		}
	}
	
	
	
	public static String getRandStr(int n){
		Random random = new Random();
		String sRand = "";
		for (int i = 0; i < n; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
		}
		return sRand; 
	}
	
	/**
	 * 得到一个数字的大写(一到十之内)
	 * @param num
	 * @return
	 */
	public static String getChineseNum(int num){
		String[] chineseNum = new String[]{"一","二","三","四","五","六","七","八","九","十"};
		return chineseNum[num];
	}

	
	public static String replaceEnter(String str){
		if(str==null) return null;
		return str.replaceAll("\r", "").replaceAll("\n", "");
	}
	
	
	public static String replaceAll(String source,String target,String content){
		StringBuffer buffer = new StringBuffer(source);
		int start = buffer.indexOf(target);
		if(start>0){
			source = buffer.replace(start, start+target.length(), content).toString();
		}
		return source;
	}
	
	/**
	 * 去除HTML 元素
	 * 
	 * @param element
	 * @return
	 */
	public static String getTxtWithoutHTMLElement(String element) {

		if (null == element || "".equals(element.trim())) {
			return element;
		}

		Pattern pattern = Pattern.compile("<[^<|^>]*>");
		Matcher matcher = pattern.matcher(element);
		StringBuffer txt = new StringBuffer();
		while (matcher.find()) {
			String group = matcher.group();
			if (group.matches("<[\\s]*>")) {
				matcher.appendReplacement(txt, group);
			} else {
				matcher.appendReplacement(txt, "");
			}
		}
		matcher.appendTail(txt);
		String temp = txt.toString().replaceAll("\n", "");
		temp = temp.replaceAll(" ", "");
		return temp;
	}
	
	/**
	 * clear trim to String 
	 * @return
	 */
	public static String toTrim(String strtrim){
		if (null != strtrim && !strtrim.equals("")) {
			return strtrim.trim();
		}
	   return "";
	}
	
	/**
	 * 转义字串的$
	 * @param str
	 * @return
	 */
	public static String filterDollarStr(String str) {
		  
		  String sReturn ="";
		  if (!toTrim(str).equals("")) {
		   
		   
		   if(str.indexOf('$', 0)>-1)
		   {
		    while(str.length()>0)
		    {
		     if(str.indexOf('$', 0)>-1)
		     {
		            sReturn +=str.subSequence(0, str.indexOf('$', 0));
		            sReturn+="\\$";
		            str =str.substring(str.indexOf('$', 0)+1, str.length());
		     }
		     else
		     {
		      sReturn+=str;
		      str="";
		     }
		      
		    }
		    
		    
		   }
		   else
		   {
		    
		    sReturn = str;
		   }
		   
		   

		  }
		  return sReturn;
		 } 

	
	public static String compressHtml(String html){
		if(html==null) return null;
		
		html = html.replaceAll("[\\t\\n\\f\\r]", "");
		return html;
	}
	
	public static String toCurrency(Double d){
		if(d != null){
			DecimalFormat df = new DecimalFormat("￥#,###.00");
			return df.format(d);
		}
		return "";
	}
	
	public static String toString(Integer i){
		if(i != null){
			return String.valueOf(i);
		}
		return "";
	}
	
	public static String toString(Double d){
		if(null != d){
			return String.valueOf(d);
		}
		return "";
	}
	
	/**
	 * 取文件后缀名
	 * @param srcpath
	 * @return
	 */
	public static String getExt(String srcpath) {
		// TODO Auto-generated method stub
		if(srcpath != null && srcpath.length()>2){
			String suffix =  srcpath.lastIndexOf(".") > 0 ? srcpath.substring(srcpath.lastIndexOf(".")+1) : null;
			return suffix;
		}
		return null;
	}
	
	/**
	 * 得到文件名
	 * @param srcpath
	 * @return
	 */
	public static String getFileName(String srcpath) {
		// TODO Auto-generated method stub
		if(srcpath != null && srcpath.length()>2){
			String fileName = srcpath.lastIndexOf("/") > 0? srcpath.substring(srcpath.lastIndexOf("/")+1) : srcpath; 
			return fileName;
		}
		return null;
	}
	
	/**
	 * 得到文件名
	 * @param srcpath
	 * @return
	 */
	public static String getFileNameExcludeSuffix(String srcpath) {
		// TODO Auto-generated method stub
		if(srcpath != null && srcpath.length()>2){
			String fileName =  srcpath.lastIndexOf(".") > 0 ? srcpath.substring(0,srcpath.lastIndexOf(".")) : srcpath;
			return fileName;
		}
		return null;
	}
	
	public static String string2Json(String s) {     
		StringBuffer sb = new StringBuffer ();     
	    for (int i=0; i<s.length(); i++) {     

	        char c = s.charAt(i);     
	        switch (c) {     
		        case '\"':     
		            sb.append("\\\"");     
		            break;     
		        case '\\':     
		            sb.append("\\\\");     
		            break;     
		        case '/':     
		            sb.append("\\\\/");     
		            break;     
		        case '\b':     
		            sb.append("\\b");     
		            break;     
		        case '\f':     
		            sb.append("\\f");     
		            break;     
		        case '\n':     
		            sb.append("\\n");     
		            break;     
		        case '\r':     
		            sb.append("\\r");     
		            break;     
		        case '\t':     
		            sb.append("\\t");     
		            break;     
		        default:     
		            sb.append(c);     
	        }
	   }
	   return sb.toString();     
	}  
	
	public static void main(String[] args) {
		System.out.println(getRandStr(6));
	}
	
}
